package web;

import domain.cms.AbstractPage;
import domain.cms.CmsPage;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.user.CmsUserService;
import web.commons.CmsLink;

import java.util.List;

public final class SearchCmsPanel extends Panel {

    private final static int RESULTS_ON_PAGE = 10;  //strankujeme po 10
    @SpringBean
    private CmsUserService cmsUserService;
    private PageParameters params;
    private IModel<List<? extends AbstractPage>> pages =
            new LoadableDetachableModel<List<? extends AbstractPage>>() {

                @Override
                protected List<? extends AbstractPage> load() {
                    return cmsUserService.search(params.getString("0"));
                }
            };

    public SearchCmsPanel(String id) {
        super(id);
        WebMarkupContainer container = new WebMarkupContainer("container");
        add(container);
        container.setVisible(false);

        add(new EmptyPanel("paging"));
    }

    public SearchCmsPanel(String id, PageParameters params) {
        super(id);
        this.params = params;


        PageableListView listView = new PageableListView<AbstractPage>("list", pages, RESULTS_ON_PAGE) {

            @Override
            protected void populateItem(ListItem item) { //model pro radek (item) je uzivatel
                //do radku zobrazime popisky atributu firmy
                //odkaz na detail
                String content = getLimitedString(((CmsPage) item.getModelObject()).getContent());
                item.add(new Label("content", content).setEscapeModelStrings(false));
                item.add(new CmsLink("link", (CmsPage) item.getModelObject()));

            }

            private String getLimitedString(String string) {
                if (string.length() > 200) {
                    string = string.substring(0, 200);

                }
                return string;
            }
        };
        //pridame strankovani
        //musime v HTML oznacit cast, ktera se ma pres ajax aktualizovat (cela tabulka)
        WebMarkupContainer container = new WebMarkupContainer("container");

        container.setOutputMarkupId(true);

        add(container);

        container.add(listView); //do kontejneru pridame seznam

        add(new AjaxPagingNavigator("paging", listView));
    }
}
